﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Util.Panels;

namespace Util.Layout.Test
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Identity
        private static IDictionary<string, Type> _viewDic;
        private static IDictionary<string, Type> _viewModelDic;

        static MainWindow()
        {
            _viewDic = new Dictionary<string, Type>();
            _viewModelDic = new Dictionary<string, Type>();
            var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("Util.Layout"));
            assembly.GetTypes().Where(x => x.Namespace.StartsWith("Util.Layout.Test.Views") && x.IsSubclassOf(typeof(UserControl))).ToList().ForEach(x => _viewDic.Add(x.Name.Remove(x.Name.Length - 4), x));
            assembly.GetTypes().Where(x => x.Namespace.StartsWith("Util.Layout.Test.ViewModels") && x.Name.Contains("ViewModel")).ToList().ForEach(x => _viewModelDic.Add(x.Name.Remove(x.Name.Length - 9), x));
        }
        #endregion

        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            listbox.ItemsSource = _viewDic.Keys.ToList();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ListBox_SelectionChanged(null, null);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            var tag = button.Content?.ToString();

            ShowContent(tag);
        }

        private void ShowContent(string tag)
        {
            if (tag == null) return;

            if (_viewDic.ContainsKey(tag))
            {
                var control = Activator.CreateInstance(_viewDic[tag]) as UserControl;
                if (_viewModelDic.ContainsKey(tag))
                {
                    var viewmodel = Activator.CreateInstance(_viewModelDic[tag]);
                    if (viewmodel != null)
                    {
                        control.DataContext = viewmodel;
                    }
                }
                ContentControl.Content = control;
            }
            else
                ContentControl.Content = null;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsLoaded)
                return;

            var tag = listbox.SelectedItem as string;

            ShowContent(tag);
        }
    }


}
